if(length(tryCatch(list.dirs(path="~/Library/CloudStorage/Dropbox/Robots and Trade in Services"),error=function(e) e))==0){
  base.path<-"~/Dropbox/Robots and Trade in Services/"
} else {
  base.path<-"~/Library/CloudStorage/Dropbox/Robots and Trade in Services/"
}

#Load data and functions
source(paste0(base.path,"Drafts/Replication/03 Functions and Processing.R"))

#############
## Table 2 ##
#############

lucid.proc$treatment_fdal_dabase = relevel(lucid.proc$treatment_fdal, ref=2)

run_analysis<-function(depvar,controls=FALSE,subsample=TRUE,return_lm_robust=TRUE){
  
  if(controls==TRUE){
    control_str<-balance_controls_vec
  } else if(class(controls) == "character"){
    control_str<-controls
  } else {
    control_str<-NULL
  }
  
  fmla<-as.formula(paste(c(paste0(depvar, " ~ treatment_fdal_dabase + sample_date"), control_str), collapse="+"))
  
  ols<-lm(fmla,data=filter(lucid.proc,{{subsample}}))
  
  return(ols)
  
}

lucid.proc$policy_difference <- ifelse(lucid.proc$treatment_automation_labor=="Labor",lucid.proc$restrict_imports_difference,lucid.proc$restrict_automation_difference)

main_models<-list(
  run_analysis(depvar="policy_difference",subsample=treatment_fdal_dabase %in% c("Domestic Automation","Foreign Labor")),
  run_analysis(depvar="policy_difference",controls=TRUE,subsample=treatment_fdal_dabase %in% c("Domestic Automation","Foreign Labor")),
  run_analysis(depvar="restrict_automation_difference",subsample=treatment_fdal_dabase %in% c("Domestic Automation","Foreign Automation")),
  run_analysis(depvar="restrict_automation_difference",controls = TRUE,subsample=treatment_fdal_dabase %in% c("Domestic Automation","Foreign Automation"))
)

stargazer::stargazer(
  main_models,
  se=estimatr::starprep(main_models),
  p=estimatr::starprep(main_models,stat="p.value"),
  add.lines = list(c("Controls","No","Yes","No","Yes"),c("Subsample","DA + FL","DA + FL","DA + FA","DA + FA")),
  keep="treatment|sample",
  dep.var.labels=c(
    "\\makecell{relevant \\\\ policy \\\\ difference}",
    "\\makecell{restrict \\\\ automation \\\\ difference}"
  ),
  keep.stat="n", 
  covariate.labels=c("Foreign Labor","Foreign Automation","Sept Sample"),
  header = FALSE,
  label = "tab:flvsdareg",
  title = "Effect of Shock Type on Preferred Response (policy minus transfers)",
  type="latex"
)
